import {EventEmitter, Injectable} from '@angular/core';
import {Router, Routes} from '@angular/router';
import {adSystemApiUrl, tuikeSystemUrl} from '../../../../config/api';
import {HttpService} from '../http.service';

@Injectable()
export class MenuService {

  public eventbus: EventEmitter<any> = new EventEmitter<any>();
  public menus: any;

  constructor(private router: Router, private httpService: HttpService) {
  }

  // 获取Menu
  getMenu() {
    const url = `${tuikeSystemUrl}/api/v1/admin/rbac/get_admin_show_permissions`;
    return this.httpService.httpPostAuth(url,{}).map(data => data);
    // const url = 'http://118.178.227.204:8091' + `/v1/common/getMenu`; // 临时端口，正式替换成adSystemApiUrl
    // return this.httpService.httpGetAuth(url).map(data =>
    //   data
    // );
  }

  public updateMenu(routes) {
    this.menus = routes;
    // console.log(this.menus);
  }

  public getCurrentMenuItemTitle(path: string) {

    let arrUrl1 = '';
    arrUrl1 = path.substring(0, path.indexOf('?'));

    let arrUrl: any;
    if (arrUrl1 !== '') {
      arrUrl = arrUrl1.split('/');
    } else {
      arrUrl = path.split('/');
    }

    // const arrUrl = arrUrl1.split('/');

    let _path = '';
    if (!this.menus) {
      return;
    }
    // console.log(arrUrl);
    this.menus.forEach((items) => {
      if (!items) {
        return;
      }
      items.forEach((item) => {
        if (arrUrl[1] === item.path) {
          _path = item.title;
          item.children.forEach((ite) => {
            if (arrUrl[2] === ite.path) {
              _path = ite.title;
              if (ite.children) {
                ite.children.forEach((it) => {
                  if (arrUrl[3] === it.path) {
                    _path = it.title;
                  }
                });
              }
            }
          });
        }
      });
    });
    // console.log(_path);
    return _path;
  }
}
